package com.rambo.cxf.spring.demo.handler;


import org.apache.wss4j.common.ext.WSPasswordCallback;

import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class CXFServerAuthHandler implements CallbackHandler {
    private static final Map<String, String> userMap = new HashMap<String, String>();

    static {
        userMap.put("user1", "111111");
        userMap.put("user2", "222222");
    }

    public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
        for (Callback callback : callbacks) {
            WSPasswordCallback pc = (WSPasswordCallback) callback;
            String clientUsername = pc.getIdentifier();
            String serverPassword = userMap.get(clientUsername);

            int usage = pc.getUsage();
            if (usage == WSPasswordCallback.USERNAME_TOKEN) {
                pc.setPassword(serverPassword);
            } else if (usage == WSPasswordCallback.SIGNATURE) {
                pc.setPassword(serverPassword);
            }
        }
    }
}